/*
 * =====================================================================================
 *
 *       Filename:  acceptor.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  07/23/2012 08:47:16 PM
 *       Revision:  none
 *       Compiler:  gcc/g++
 *
 *         Author:  wangtengchao , wangtengchao AT gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */

#include "acceptor.h"
#include "netHelp.h"
#include "dispatcher.h"
#include "timestamp.h"
#include<errno.h>
#ifdef NET_DEBUG
#include <cstdio>
#endif

using namespace inm::net;


Acceptor::Acceptor(std::string name,Dispatcher *dispatcher, const InetAddr &serverAddr)
    :EventHandler(name,dispatcher),
      listenAddr_(serverAddr),
      listenSocket_(serverAddr)
{


}

Acceptor::Acceptor(std::string name,Dispatcher* dispatcher,const InetAddr &serverAddr,const NewConnectCallback& cb)
    :EventHandler(name,dispatcher),
      listenAddr_(serverAddr),
      listenSocket_(serverAddr),
      newConnectCallBack_(cb)
{

    //dispatcher_->registerHandler(shared_from_this(),ACCEPT_EVENT);
}
void Acceptor::listen()
{

    listenSocket_.listen();
}


void Acceptor::handleRead()
{
#ifdef NET_DEBUG
    printf("Acceptor handleRead port %d \n",listenAddr_.getPort());
#endif
    InetAddr newClientAddr(0);
    int connfd ;

    if((connfd = listenSocket_.accept(newClientAddr)) >0)
    {
         if(connfd > 0)
         {
            //write connect log
#ifdef NET_DEBUG
             printf("new connect from %s port %d\n",InetNumericToPresentation(newClientAddr.getInAddrT()).c_str(),newClientAddr.getPort());
#endif
             inm::net::SetNonBlock(connfd);
             Timestamp t = Timestamp::now();
             if(newConnectCallBack_)
                 newConnectCallBack_(connfd,newClientAddr,t);//newClientAddr not include connfd,so should padd two arguments
         }
    }
    /*
    //for epoll ET  should change if to while
    if(connfd == -1)
    {//if connfd==-1  && errno=EAGAIN   means accept all connections
        if (errno != EAGAIN && errno != ECONNABORTED
                  && errno != EPROTO && errno != EINTR)
            printf("Accept Error %d",errno);
    }
    */
}
void Acceptor::handleClose()
{

}
